package com.fzdy.dataplatform.webutil;

import com.fzdy.dataplatform.cache.EncacheHelper;
import com.fzdy.dataplatform.entity.User;
import net.sf.ehcache.Element;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.servlet.http.HttpServletRequest;
import java.util.Map;

@Service
public class WebUtilify {

    //    private static Map<String,LoginUserInfo> map=AllModule.loginUserInfoMap;
    @Autowired
    private EncacheHelper encacheHelper;


    public User LoginUserinfo(HttpServletRequest request) {
        String apikey = request.getHeader("apikey");
        LoginUserInfo loginUserInfo = (LoginUserInfo) encacheHelper.get(apikey);
        return loginUserInfo.getUser();
    }

    public Boolean isAdmin(HttpServletRequest request) {
        String apikey = request.getHeader("apikey");
        if (apikey == null) {
            return null;
        }
        LoginUserInfo loginUserInfo = (LoginUserInfo) encacheHelper.get(apikey);
        if (loginUserInfo == null) {
            return null;
        }
        return loginUserInfo.getAdmin();
    }

    public void delLoginInfo(HttpServletRequest request) {
        String apikey = request.getHeader("apikey");
        encacheHelper.put(apikey, null);
    }

    public int[] LoginUserRight(HttpServletRequest request) {
        String apikey = request.getHeader("apikey");
        LoginUserInfo loginUserInfo = (LoginUserInfo) encacheHelper.get(apikey);
        return loginUserInfo.getRingtIds();
    }

    public void putLoginInfo(String api, LoginUserInfo loginUserInfo) {
        encacheHelper.put(api, loginUserInfo);
    }

    public void delByUserid(Integer userid) {
        Map<Object, Element> map = encacheHelper.getAll();
        for (Object key : map.keySet()) {
            Object obj = map.get(key).getObjectValue();
            if (obj != null) {
                LoginUserInfo loginUserInfo = (LoginUserInfo) obj;
                if (loginUserInfo.getUser().getId().equals(userid)) {
                    encacheHelper.put(key.toString(), null);
                }
            }
        }
    }

}
